
package it.csttech.date;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.ext.ParamConverter;

import org.apache.commons.validator.routines.FloatValidator;
/**
 * OVERVIEW
 * This class provides a converter for floats
 * @author marcello.felappi
 * @author marco.dalena
 */
public class FloatParamConverter implements ParamConverter<Float> {
/**
 * Object representing the request from the client
 */
	private HttpServletRequest request;
/**
 * This method represents a constructor for  the  FloatParamConverter class
 * @param request
 */
	public FloatParamConverter(HttpServletRequest request) {

		this.request = request;
	}
	/**
	 * Method used to transform a float in a string
	 * @param number - float parameter
	 * @return the string converted from the float input
	 */
	@Override
	public String toString(Float number) {

		Locale locale = request.getLocale();

		NumberFormat format = DecimalFormat.getInstance(locale);
		return format.format(number);
	}
	/**
	 * Method used to translate the string parameter in a float according to the locale of the request
	 * @param input - string representing the parameter value
	 * @throws IllegalArgumentException - thrown because of an error parsing the float
	 * @return the float converted from the string input according to the locale of the request
	 */
	@Override
	public Float fromString(String input) {

		Locale locale = request.getLocale();

		NumberFormat format = DecimalFormat.getInstance(locale);
		FloatValidator validator = new FloatValidator();

		try {
			if (validator.validate(
				input, ((DecimalFormat) format).toPattern(), locale) != null) {
				Number number = format.parse(input);
				return number.floatValue();
			}
			else
			{
				
				throw new IllegalArgumentException(Messages.getString("ErrorCode.wrongFloatFormat"));
			}
		}
		catch (ParseException e) {
			
			throw new IllegalArgumentException(Messages.getString("ErrorCode.wrongFloatFormat"));
		}

	}

}
